import os
from dotenv import load_dotenv
import pymysql
pymysql.install_as_MySQLdb()

# 加载环境变量
load_dotenv()

DEBUG = os.getenv('DEBUG', 'True') == 'True'
ALLOWED_HOSTS = os.getenv('ALLOWED_HOSTS', '').split(',')

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.getenv('SECRET_KEY', 'django-insecure-your-secret-key-here')

# 主要设置部分
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    # 第三方应用
    'rest_framework',
    'corsheaders',
    'django_filters',

    # 自定义应用
    'apps.user',
    'apps.product',
    'apps.order',
    'apps.delivery',
    'apps.member',
    'apps.cart',
    'apps.address',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    # 添加本地化中间件
    'django.middleware.locale.LocaleMiddleware',
    'corsheaders.middleware.CorsMiddleware',  # 添加CORS中间件
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

# REST Framework设置
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    ],
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.AllowAny',
    ],
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 10
}

# CORS设置
# 从 ALLOWED_HOSTS 生成 CORS 和 CSRF 设置
CORS_ALLOWED_ORIGINS = []

# 添加默认值
default_origins = [
    "http://localhost:8080",
    "http://127.0.0.1:8000",
    "http://localhost:8000",
    "https://api.guguxiang.xin"
]

# 添加来自ALLOWED_HOSTS的值
for host in ALLOWED_HOSTS:
    if host and host.strip():
        CORS_ALLOWED_ORIGINS.append(f"http://{host.strip()}")
        if not DEBUG:  # 在生产环境中添加HTTPS
            CORS_ALLOWED_ORIGINS.append(f"https://{host.strip()}")

# 添加默认值
CORS_ALLOWED_ORIGINS.extend(default_origins)

# CSRF设置
CSRF_TRUSTED_ORIGINS = CORS_ALLOWED_ORIGINS.copy()

# 输出调试信息
if DEBUG:
    print("ALLOWED_HOSTS:", ALLOWED_HOSTS)
    print("CORS_ALLOWED_ORIGINS:", CORS_ALLOWED_ORIGINS)
    print("CSRF_TRUSTED_ORIGINS:", CSRF_TRUSTED_ORIGINS)

# 允许Cookie跨域
CORS_ALLOW_CREDENTIALS = True

# Cookie设置
SESSION_COOKIE_SECURE = False  # 开发环境设置为False
CSRF_COOKIE_SECURE = False    # 开发环境设置为False
CSRF_COOKIE_HTTPONLY = True   # 防止JavaScript访问CSRF cookie
CSRF_USE_SESSIONS = True      # 将CSRF token存储在session中
SESSION_COOKIE_HTTPONLY = True # 防止JavaScript访问Session cookie

# 自定义CSRF验证失败视图
CSRF_FAILURE_VIEW = 'utils.views.csrf_failure'

# 数据库设置
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': os.getenv('DB_NAME', 'delivery_system'),
        'USER': os.getenv('DB_USER', 'root'),
        'PASSWORD': os.getenv('DB_PASSWORD', ''),
        'HOST': os.getenv('DB_HOST', 'localhost'),
        'PORT': os.getenv('DB_PORT', '3306'),
        'OPTIONS': {
            'init_command': "SET sql_mode='STRICT_TRANS_TABLES'",
            'charset': 'utf8mb4'
        }
    }
}

# 添加自定义用户模型
AUTH_USER_MODEL = 'user.User'

# 媒体文件配置
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

# 静态文件配置
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')

# JWT配置
from datetime import timedelta
SIMPLE_JWT = {
    'ACCESS_TOKEN_LIFETIME': timedelta(days=1),
    'REFRESH_TOKEN_LIFETIME': timedelta(days=7),
    'ROTATE_REFRESH_TOKENS': False,
    'ALGORITHM': 'HS256',
    'SIGNING_KEY': SECRET_KEY,
    'AUTH_HEADER_TYPES': ('Bearer',),
}

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],  # 添加模板目录
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

# 语言和时区设置
LANGUAGE_CODE = 'zh-hans'  # 简体中文
TIME_ZONE = 'Asia/Shanghai'  # 中国时区
USE_I18N = True  # 启用国际化
USE_L10N = True  # 本地化日期和数字格式
USE_TZ = True  # 启用时区支持

# 自定义Admin站点标题和头部
ADMIN_SITE_HEADER = '谷香外卖系统管理后台'
ADMIN_SITE_TITLE = '谷香外卖系统'
ADMIN_INDEX_TITLE = '系统管理'

# 微信小程序配置
WX_APP_ID = os.getenv('WX_APP_ID', '')
WX_APP_SECRET = os.getenv('WX_APP_SECRET', '')

# 添加 ROOT_URLCONF 配置
ROOT_URLCONF = 'core.urls'  # 假设你的项目名为 'core'

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
        },
        'file': {
            'class': 'logging.FileHandler',
            'filename': 'debug.log',
        },
    },
    'root': {
        'handlers': ['console', 'file'],
        'level': 'INFO',
    },
}